package com.sajus.web.billing.ejb.data.model;

import java.io.Serializable;
import java.lang.reflect.Field;

import javax.persistence.PostPersist;
import javax.persistence.Transient;


abstract public class PersistentObject implements Serializable  {

	/* by default consider the entity as being persisted */
	@Transient
	private boolean isPersisted = true;

	/* convenience method*/
	public boolean isNew() {
		return !isPersisted();
	}
	public boolean isPersisted() {
		return isPersisted;
	}

	public void setPersisted(boolean isPersisted) {
		this.isPersisted = isPersisted;
	}
	
	@PostPersist
	public void onPostPersist() {				
		this.isPersisted = true;
		System.out.println("callback is being called");
	}

	public Integer getId(){
		return new Integer(0);
	}
	public String toString() {
		StringBuffer str = new StringBuffer();
		str.append(this.getClass().getName() + " {");
		Field[] fields = this.getClass().getDeclaredFields();
		for (Field field : fields) {
			try {
				String fieldType = field.getType().getName();
				if (fieldType.contains("qsm.") && fieldType.endsWith("PK") == false) {
					continue;
				}
				field.setAccessible( true );
				str.append("[" + field.getName() + "=" + field.get( this ) + "],");
			} catch (Exception e) {
			}
		}
		return str.toString();
	}
	
	public String getKeyInfo() {
		Object id = TransactionContext.getTransactionContext().getEm().getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier( this );
		return id.toString();
	}	

	public void detach() {
		TransactionContext txCtx = TransactionContext.getTransactionContext();
		if (txCtx != null) {
			txCtx.getEm().detach( this );
		}
	}

	public PersistentObject attach() {
		TransactionContext txCtx = TransactionContext.getTransactionContext();
		if (txCtx != null) {
			return txCtx.getEm().merge( this );
		}
		return this;
	}

	public void remove() {
		if (isPersisted) {
			TransactionContext.getTransactionContext().getEm().remove( this );
		}
		setPersisted( false );
	}
}
